package com.Ugent.Minerva;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.KeepAliveHttpsTransportSE;


public class Soap {
	
	public static Object login (String user, String pass){

		//request voor ticket
		SoapObject request = new SoapObject("http://minerva.ugent.be/api/", "login");
		request.addProperty("username", user);
		request.addProperty("password", pass);
		Object result = Soap.transport("http://minerva.ugent.be/api/login", request);
		return result;
	}
	
	public static Object identifyUser (String ticket){
		//request voor user
		SoapObject request = new SoapObject("http://minerva.ugent.be/api/", "identify_user");
		request.addProperty("ticket", ticket);
		Object result = Soap.transport("http://minerva.ugent.be/api/identify_user", request);
		return result;
	}
	
	public static Object getCourseList (String officialCode){
		//request voor courselist
		SoapObject request = new SoapObject("http://minerva.ugent.be/api/", "get_course_list");
		request.addProperty("official_code", officialCode);
		Object result = Soap.transport("http://minerva.ugent.be/api/get_course_list", request);
		return result;
	}
    
	public static Object getToolContent (String code, String tool){
		//request voor tools
		SoapObject request = new SoapObject("http://minerva.ugent.be/api/", "get_tool_content");
		request.addProperty("course_code", code);
		request.addProperty("tool", tool);
		Object result = Soap.transport("http://minerva.ugent.be/api/get_tool_content", request);
		return result;
	}
	public static Object getActiveTools (String courseCode){
		//request voor tools
		SoapObject request = new SoapObject("http://minerva.ugent.be/api/", "get_active_tools_for_course");
		request.addProperty("course_code", courseCode);
		Object result = Soap.transport("http://minerva.ugent.be/api/get_active_tools_for_course", request);
		return result;
	}

	
    public static Object transport (String soapAction, SoapObject request) {
    	Object result = null;
    	//envelope maken
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
		envelope.env = "http://schemas.xmlsoap.org/soap/envelope/";
		envelope.encodingStyle = SoapSerializationEnvelope.ENC;
		envelope.setAddAdornments(false);
		envelope.dotNet = true;
		envelope.bodyOut = request;
		envelope.setOutputSoapObject(request);
		
		//basic authorisation
		List<HeaderProperty> headerPropertyList = new ArrayList<HeaderProperty>();
        headerPropertyList.add(new HeaderProperty("Authorization", "Basic eXByc3NsZXI6NDZkOGU3M2U3NDJjZjE2MWYwZjU5MDRiNTU0ZDQ1YjY="));
     
        //transport
        KeepAliveHttpsTransportSE androidHttpTransport = new KeepAliveHttpsTransportSE ("minalpha.ugent.be", 443, "/api/index.php", 10000); 
		androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
		androidHttpTransport.debug = true; 
		FakeX509TrustManager.allowAllSSL(); // this class may allow SSL
		
		try {
			androidHttpTransport.call(soapAction, envelope, headerPropertyList);
			
			System.out.println("request: " + androidHttpTransport.requestDump);
            System.out.println("response:" + androidHttpTransport.responseDump);
            	                    
            result = envelope.getResponse();
            return result;
            
            

		} catch (Exception e) {
			result = "error";
			 return result;
			
		}
    	
    	
    }
    // 
	static class FakeX509TrustManager implements X509TrustManager {
		private static TrustManager[] trustManagers;
		private final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};

		public void checkClientTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
		}

		public boolean isClientTrusted(X509Certificate[] chain) {
			return true;
		}

		public boolean isServerTrusted(X509Certificate[] chain) {
			return true;
		}

		public X509Certificate[] getAcceptedIssuers() {
			return _AcceptedIssuers;
		}

		public static void allowAllSSL() {
			HttpsURLConnection
					.setDefaultHostnameVerifier(new HostnameVerifier() {

						public boolean verify(String hostname,
								SSLSession session) {
							return true;
						}
					});
			SSLContext context = null;
			if (trustManagers == null) {
				trustManagers = new TrustManager[] { new FakeX509TrustManager() };
			}
			try {
				context = SSLContext.getInstance("TLS");
				context.init(null, trustManagers, new SecureRandom());
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (KeyManagementException e) {
				e.printStackTrace();
			}
			HttpsURLConnection.setDefaultSSLSocketFactory(context
					.getSocketFactory());
		}

	}
	
}

